<?php

namespace App\Admin\Middleware;

use App\Admin\Exceptions\AdminException;
use App\Admin\Services\GrantService;
use Closure;
use Illuminate\Support\Facades\URL;

class PermissionMiddleware
{
    /**
     * 权限验证
     */
    public function handle($request, Closure $next)
    {
        // 白名單
        $white = ['login', 'logout'];
        if (in_array(request()->route()->uri, $white)) {
            return $next($request);
        }

        // 沒有定義 description 則不走權限檢測
        if (!request()->route()->getActionDescription()) {
            return $next($request);
        }

        // 獲取session中的admin信息
        $admin = auth('admin')->user();
        $route = request()->route()->getName();

        if (!$admin || !$admin->hasPermissionForRoute($route)) {
            // 没有权限访问
            throw new AdminException('没有权限访问', 403, URL::previous());
        }

        return $next($request);
    }
}
